<html>
<head>
    <meta charset="utf-8">
    <title>Work Order</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="{{manager_static_path()}}/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="{{manager_static_path()}}/style/admin.css" media="all">
    <link id="layuicss-layer" rel="stylesheet"
          href="{{manager_static_path()}}/layui/css/modules/layer/default/layer.css?v=3.1.1" media="all">
    <link id="layuicss-skinlayimcss" rel="stylesheet"
          href="{{manager_static_path()}}/layui/css/modules/layim/layim.css?v=3.8.0" media="all">
    <style>
        body,html{
            height: 100%;
        }
        .box{
            height: 100%;
            margin: 0;
            padding: 0;
            display: flex;
            flex-direction: column;
            width: 100%;background: #fff;
        }
        .layui-layer-content{
            flex-grow: 1;
            overflow-y: auto;
        }
        .chat-title{
            height: 60px;
            background: #e6e6e6;
        }
        .layim-chat-other{
            height: 100%;align-items: center;display: flex;
        }
        .chat-title .layim-chat-other img{
            width: 40px;height: 40px;
        }
        .layim-send-close{
            background: #019bff !important;
        }
        .layim-chat-mine .layim-chat-text{
            background: #019bff !important;
        }
        .layim-chat-mine .layim-chat-text:after{
            display: none;
        }
        .layui-layim-photos img{
            width: 120px;height: 90px;cursor: pointer;
        }
        .layim-chat-footer{
            height: 160px;
        }
        .layim-chat-tool{padding: 0 !important;}
        .layui-layim-file{
            background: #fff;
            width: 200px;
            height: 60px;
            display: inline-flex !important;
            align-items: center;
            cursor: pointer;
        }
        .layui-layim-file .file-info{
            width: 160px;overflow: hidden; white-space: nowrap;margin: 0 5px;
            text-align: left;
        }
        .layui-layim-file .file-icon{
            width: 40px;
        }
        .layui-layim-file .layui-icon{
            font-size: 40px;
        }
        .layim-chat-mine .layim-chat-user cite i{
            padding-left: 15px;
        }
    </style>
</head>
<body>
<div class="box">
    <div class="layui-unselect chat-title">
        <div class="layim-chat-other">
            <div style="margin-left: 15px;">
                <img class="layim-friend" src="{{$icon ?? ""}}">
            </div>
            <div style="height: 60px;line-height: 60px;margin-left: 10px;"><span class="layim-chat-username">{{$title ?? ""}}</span></div>
        </div>
    </div>
    <div id="layui-layim-chat" class="layui-layer-content">
        <div class="layim-chat-box">
            <div class="layim-chat layim-chat-friend layui-show">
                <div class="layim-chat-main">
                    <ul id="message-box"></ul>
                </div>
            </div>
        </div>
    </div>
    <div class="layim-chat-footer">
        <div class="layui-unselect layim-chat-tool">
            <span class="layui-icon layim-tool-image" title="上传图片">
                <input type="file" name="file" id="send_image" accept="image/*">
            </span>
            <span class="layui-icon layim-tool-image" title="发送文件" data-type="file">
                <input type="file" name="file" id="send_file">
            </span>
        </div>
        <div class="layim-chat-textarea">
            <textarea placeholder="" id="write-message"></textarea>
        </div>
        <div class="layim-chat-bottom">
            <div class="layim-chat-send">
                <span class="layim-send-close" id="SendMessage">Send</span>
            </div>
        </div>
    </div>
</div>
</body>
</html>
<script src="{{manager_static_path()}}/layui/layui.js"></script>
<script src="/resources/js/socket.io.min.js"></script>

<script>
    layui.config({
        base: '{{manager_static_path()}}' //静态资源所在路径
    }).extend({
        index: 'lib/index' //主入口模块
    }).use(['index'],function (){
        var $ = layui.$,
            layer = layui.layer;
        var loadIndex;
        var maxTimeStamp = 0;
        var maxMessageId = 0;

        function getUrlParams(url = window.location.href) {
            const urlParams = new URL(url);
            const params = {};
            for (const param of urlParams.searchParams.entries()) {
                params[param[0]] = param[1];
            }
            return params;
        }
        function loading(){
            var loading = layer.load(2, {
                shade: [0.8, '#fff']
            });
        }
        function closeLoading(){
            layer.closeAll('loading');
        }
        function loadMessageLogs() {
            $.ajax({
                url: "/message/" + params.session,
                type: "get",
                headers: {
                    "Authorization": "Bearer " + params.key,
                },
                success: function (res) {
                    if (res.code === 200) {
                        let messages = res.data;
                        for(let i in messages){
                            addMessage(messages[i]);
                        }
                        closeLoading();
                    }
                }
            })
        }
        function scrollToBottom(){
            $("#layui-layim-chat").scrollTop($("#message-box").prop("scrollHeight"))
        }
        /*
             * 添加消息
             * @param data
             * @param isSend
             */
        function addMessage(data){
            let html = "";
            if(data.is_send){
                html = `<li class="layim-chat-mine">`;
            }else{
                html = `<li>`;
            }
            html += `<div class="layim-chat-user">` +
                `<img src="`+ data.avatar +`">` +
                `<cite>`+ data.username +`<i>` + formatTimestamp(data.create_time) + `</i></cite>` +
                `</div>`;
            let content = data.content;
            switch(content.type){
                case "text":
                    html += `<div class="layim-chat-text"><p>` + content.content + `</p></div>`;
                    break;
                case "image":
                    html += `<div class="layim-chat-text"><div class="layui-layim-photos" data-src="` + content.image.src + `" data-filename="` + content.image.filename + `"><img src="` + content.image.src + `"></div></div>`;
                    break;
                case "file":
                    html += `<div class="layim-chat-text"><div class="layui-layim-file" data-src="` + content.file.src + `" data-filename="` + content.file.filename + `"><div class="file-info"><div>` + content.file.filename + `</div><div>` + formatFileSize(content.file.file_size) + `</div></div><div class="file-icon"><i class="layui-icon layui-icon-file-b"></i></div></div></div>`;
                    break;
                default:
                    html = "";
            }
            $("#message-box").append(html);
            scrollToBottom();
            maxMessageId = data.id;
            maxTimeStamp = data.create_time;
        }

        function formatTimestamp(timestamp){
            let padZero = (num) => ('00' + num).slice(-2);
            let date = new Date(timestamp * 1000);
            let Y = date.getFullYear();
            let M = padZero(date.getMonth() + 1);
            let D = padZero(date.getDate());
            let H = padZero(date.getHours());
            let m = padZero(date.getMinutes());
            let S = padZero(date.getSeconds());
            return Y + "-" + M + "-" + D + " " + H + ":" + m + ":" + S;
        }

        function SendMessage(data){
            data.session = params.session;
            $.ajax({
                url: "/message/send",
                method: "POST",
                headers: {
                    "Authorization": "Bearer " + params.key,
                },
                data: data,
                success: function (res) {
                    if(res.code === 200){
                        let message = res.data;
                        addMessage(message);
                        layer.close(loadIndex);
                        $("#write-message").val("")
                    }else{
                        layer.msg("message send fail",{icon: 2,time: 1000,anim:6});
                        return false;
                    }
                },
                error: function(xhr, status, error) {
                    layer.msg("message send fail",{icon: 2,time: 1000,anim:6});
                    return false;
                },
                complete: function(xhr, status) {
                    layer.close(loadIndex);
                }
            });
        }

        function formatFileSize(sizeInBytes, decimalPoints = 2) {
            const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
            let i = 0;
            while (sizeInBytes >= 1024 && i < units.length - 1) {
                sizeInBytes /= 1024;
                i++;
            }
            return `${sizeInBytes.toFixed(decimalPoints)} ${units[i]}`;
        }

        function StartEventSource(){
            var source = new EventSource('/message/sse?session=' + params.session + "&key=" + params.key);
            source.addEventListener('message', function(event) {
                var data = event.data;
                let messages = JSON.parse(data);
                for(let i in messages){
                    if(maxTimeStamp < messages[i].create_time){
                        addMessage(messages[i]);
                    }
                }
            }, false);
        }

        //初始化
        const params = getUrlParams();
        if(!("session" in params) || !("key" in params)){
            let write_message = document.getElementById("write-message");
            write_message.disabled = true;
            write_message.value = "Somethings error";
            let send = document.getElementById("SendMessage");
            send.disabled = true;
        }
        loading();
        loadMessageLogs();
        // 文件点击
        $("#layui-layim-chat").on("click",".layui-layim-file",function (){
            let src = $(this).attr("data-src");
            let filename = $(this).attr("data-filename");
            var a = $('<a>', {href: src, download: filename, style: 'display:none;'});
            $('body').append(a);
            a[0].click();
            a.remove();
        });
        //图片点击
        $("#layui-layim-chat").on("click",".layui-layim-photos",function (){
            let src = $(this).attr("data-src");
            layer.photos({
                photos: {
                    "title": "查看图片",
                    "id": 123,
                    "start": 0,
                    "data": [
                        {
                            "alt": "",
                            "pid": 1,
                            "src": src,
                            "thumb": ""
                        }
                    ]
                },
                shade: 0.5,
                shadeClose: true,
                anim: 5
            });
        });
        //发送图片、文件
        $("#send_image,#send_file").on("change",function(){
            var fileInput = this;
            var files = fileInput.files;
            var url = "";

            if(files.length > 0){
                var formData = new FormData();
                formData.append("file", files[0]);
                formData.append("session", params.session);
                var file = files[0];
                var fileType = file.type;
                if (fileType.includes("image")) {
                    url = "/message/send/image";
                } else {
                    url = "/message/send/file";
                }
                var loadIndex = layer.msg("Sending...",{icon: 16,shade:0.01});
                $.ajax({
                    url: url,
                    method: "POST",
                    headers: {
                        "Authorization": "Bearer " + params.key,
                    },
                    data: formData,
                    contentType: false,
                    processData: false,
                    success: function (res) {
                        if(res.code === 200) {
                            let message = res.data;
                            addMessage(message);
                            layer.close(loadIndex);
                            $("#write-message").val("")
                        }else{
                            layer.msg("message send fail",{icon: 2,time: 1000,anim:6});
                            return false;
                        }
                    },
                    error: function(xhr, status, error) {
                        layer.msg("message send fail",{icon: 2,time: 1000,anim:6});
                        return false;
                    },
                    complete: function(xhr, status) {
                        fileInput.value = "";
                        layer.close(loadIndex);
                    }
                })
            }
        });


        $("#SendMessage").click(function(){
            let value = $("#write-message").val();
            if(value === ""){
                layer.msg("message can not be empty",{icon: 2,time: 1000,anim:6});
                return false;
            }
            loadIndex = layer.msg("Sending...",{icon: 16,shade:0.01})
            let content = {};
            content.type = "text";
            content.content = value;
            content.create_time = Math.floor(Date.now() / 1000);
            SendMessage(content);
        });
        //拉去消息记录
        StartEventSource();
    });
</script>
